﻿using BW.Demo.Domain.Entities;
using BW.Demo.ErrorCode;
using BW.Demo.Infrastructure.Interfcaes;
using BW.Demo.WebApi.Applications.Commands;
using BW.Demo.WebApi.Dtos;
using MediatR;

namespace BW.Demo.WebApi.Applications.CommandHandlers
{
    public class TraceabilityQueryCommandHandler : IRequestHandler<TraceabilityQueryCommand, APIResult<APIPaging<TraceabilityDTO>>>
    {
        private readonly IBaseRespitory<TraceabilityManagement> _traceabilityrep;
        private readonly IBaseRespitory<ProductName> _Name; 
        public TraceabilityQueryCommandHandler(IBaseRespitory<TraceabilityManagement> traceabilityrep, IBaseRespitory<ProductName> Name)
        {
            _Name = Name;
            _traceabilityrep = traceabilityrep;
        }
        public Task<APIResult<APIPaging<TraceabilityDTO>>> Handle(TraceabilityQueryCommand request, CancellationToken cancellationToken)
        {
             APIResult<APIPaging<TraceabilityDTO>> result = new APIResult<APIPaging<TraceabilityDTO>>();
            result.Code=ResultCode.查询成功;
            result.Message=ResultCode.查询成功.ToString();
            
            var list = from a in _Name.GetAll()
                       join b in _traceabilityrep.GetAll() on a.Gid equals b.Gid
                       where !b.IsDeleted 
                       select new TraceabilityDTO
                       {
                           Basic_Traceability=b.Basic_Traceability,
                           Gid=b.Gid,
                           Batch=b.Batch,
                           Shelf_life=b.Shelf_life,
                           Productionlicense=b.Productionlicense,
                           Production_Enterprise=b.Production_Enterprise,
                           Information_Completeness=b.Information_Completeness,
                           ProductInspectionReportPath=b.ProductInspectionReportPath,
                           CoverImage=b.CoverImage,
                           CreateTime=b.CreateTime,
                           CreateUser=b.CreateUser,
                           UpdateTime=b.UpdateTime,
                           UpdateUser=b.UpdateUser,
                           IsDeleted=b.IsDeleted,
                           GoodsName=a.GoodsName,

                       };
            if (request.Basic_Traceability != null)
            {
                list = list.Where(x => x.Basic_Traceability == request.Basic_Traceability);
            }
            int totalCount = list.Count();
            int totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.Size);
            list = list.OrderByDescending(x => x.CreateTime).Skip((request.Index - 1) * request.Size).Take(request.Size);
            APIPaging<TraceabilityDTO> ping = new APIPaging<TraceabilityDTO>();
            ping.TotalPage = totalPage;
            ping.TotalCount = totalCount;
            ping.PageData = list.ToList();
            result.Data = ping;
            return Task.FromResult(result);
        }
    }
}
